package com.znzz.controller;

import com.znzz.entity.Files;
import com.znzz.service.FilesService;
import com.znzz.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 文件的控制层
 */
@Controller()
@RequestMapping("/teacher")
public class FilesController {

    @Autowired
    private FilesService filesService;

    @RequestMapping("/Fileupload")
    public String fileCourse(){
        return "teacher/Files_upload";
    }

    /**
     * SpringMVC文件上传
     * @return
     */
    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    public String uploadFiles(HttpServletRequest request,@RequestParam(name = "files")MultipartFile upload) throws Exception {
        System.out.println("springmvc文件上传...");
        // 使用fileupload组件完成文件上传
        // 上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
            // 判断，该路径是否存在
            File file = new File(path);
            System.out.println(path);
            if(!file.exists()){
                // 创建该文件夹
                file.mkdirs();
            }

        // 获取上传文件的名称
        String filename = upload.getOriginalFilename();
        // 把文件的名称设置唯一值，uuid
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(27);
        String uniquefilename = uuid+"_"+filename;
        File saveFile=new File(path,uniquefilename);
        //获取文件大小
        long size=upload.getSize();
        System.out.println(size);
        String sizes=(size/1024)+"KB";
        //把上传的文件内容存入数据库
        Files files=new Files();
        files.setFileName(filename);
        files.setFileSize(sizes);
        files.setUploadTime(DateUtil.getTime(new Date()));
        files.setFilePath(saveFile.toString());
        files.setPrefixName(uniquefilename);
        files.setSuffixName(uniquefilename.substring(uniquefilename.lastIndexOf(".")+1));
        files.setDownloadCount(0L);//初次保存文件，下载次数默认为0
        if(filesService.saveFiles(files)){
            // 完成文件上传
            upload.transferTo(new File(path,uniquefilename));
            request.setAttribute("msg","上传文件成功");
            return "msg/success";
        }else{
            request.setAttribute("msg","上传文件失败");
            return "msg/failure";
        }
    }

    /**
     * 上传的文件的详细信息
     * @param page
     * @param pageSize
     * @param request
     * @return
     */
    @RequestMapping("t-showdetailFile")
    public String List(Integer page,Integer pageSize,HttpServletRequest request){
        int count =filesService.getFilesCountById();
        System.out.println("count:"+count);
        if(pageSize == null){
            pageSize=10;
        }
        Integer allPages = count%pageSize==0?count/pageSize:count/pageSize+1;
        if(page==null || page<0){
            page=1;
        }else if(page>allPages){
            page=allPages;
        }
        List<Files> files=filesService.getFilesById4Page(page,pageSize);
        request.setAttribute("files",files);
        request.setAttribute("page",page);
        request.setAttribute("pageSize",pageSize);
        request.setAttribute("count",count);
        request.setAttribute("allPages",allPages);
        return "teacher/Files_download";
    }

    /**
     * 文件详情
     * @param request
     * @param mv
     * @param uid
     * @return
     */
    @RequestMapping("/t-details.action")
  public ModelAndView getFilesById(HttpServletRequest request, ModelAndView mv, @RequestParam("id")Integer uid){
        Files file=filesService.getFilesById(uid);
        System.out.println("file:"+file);
        mv.addObject("fileItem",file);
        mv.setViewName("teacher/Files_detail");
        return mv;
  }

    /**
     * 下载文件
     * @param id
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
  @RequestMapping("/t-download.action")
  public void downloadFile(@RequestParam(value = "id")Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException {
      Files fileItem=filesService.getFilesById(id);
      Long count=fileItem.getDownloadCount()+1L;
      fileItem.setDownloadCount(count);
      filesService.updatedownloadCount(fileItem);

      InputStream inputStream;
      BufferedOutputStream bufferedOutputStream;

      //通过id找到该文件，并得到文件的名字
      String PrefixName=filesService.getFilesById(id).getPrefixName();
      String fileName=filesService.getFilesById(id).getFileName();
      String path=request.getSession().getServletContext().getRealPath("/uploads")+"\\"+PrefixName;
      System.out.println("path:"+path);

      //将保存路径作为文件路径
      File file =new File(path);
      //如果文件存在
      if(file.exists()){
          //得到文件输入流
          inputStream =new BufferedInputStream(new FileInputStream(file));
          //避免中文乱码
          String filename= URLEncoder.encode(fileName,"utf-8");
          //设置页面不缓存，清空buffer
          response.reset();
          //设置文件下载头
          response.setHeader("Content-Disposition","attachment;fileName="+filename);
          //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
          response.setContentType("multipart/form-data");
          //获取文件输出流
          bufferedOutputStream= new BufferedOutputStream(response.getOutputStream());
          int len;
          while ((len=inputStream.read())!=-1){
              bufferedOutputStream.write(len);
              bufferedOutputStream.flush();
          }
          inputStream.close();
          bufferedOutputStream.close();
          response.sendRedirect(request.getContextPath()+"teacher/t-showdetailFile");
          return;
      }

  }

    /**
     * 删除文件，以及数据库保留的数据
     * @param id
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
  @RequestMapping("/t-deleteFile.action")
  public void deleteFile(@RequestParam("id")Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //先删除本地磁盘存入的文件，不能先删除数据库的
      Files files=filesService.getFilesById(id);
      System.out.println("files:"+files);
      File file=new File(files.getFilePath());
      if(file.isFile() && file.exists()){
          if(file.delete()){
              filesService.deleteFile(id);
              response.sendRedirect(request.getContextPath()+"/teacher/t-showdetailFile");
              return;
          }else {
              request.getRequestDispatcher("/WEB-INF/Page/msg/failure.jsp").forward(request,response);
          }
      }else {
          System.out.println("该文件不存在");
          return;
      }
  }
}
